const { Material, User, Payment, Download, Log } = require('../models')
const { Op } = require('sequelize')

class AdminController {
  // 获取仪表盘统计数据
  async getDashboardStats(req, res) {
    try {
      // 获取总用户数
      const userCount = await User.count()
      
      // 获取总资料数
      const materialCount = await Material.count()
      
      // 获取总下载量
      const downloadCount = await Download.sum('count') || 0
      
      // 获取总收入
      const totalIncome = await Payment.sum('amount') || 0
      
      // 获取最近30天收入趋势
      const thirtyDaysAgo = new Date()
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
      
      const incomeTrend = await Payment.findAll({
        where: {
          status: 'paid',
          createdAt: { [Op.gte]: thirtyDaysAgo }
        },
        attributes: [
          [sequelize.fn('DATE', sequelize.col('createdAt')), 'date'],
          [sequelize.fn('SUM', sequelize.col('amount')), 'total']
        ],
        group: [sequelize.fn('DATE', sequelize.col('createdAt'))],
        order: [[sequelize.fn('DATE', sequelize.col('createdAt')), 'ASC']]
      })
      
      // 获取资料分类分布
      const categoryDistribution = await Material.findAll({
        include: ['category'],
        attributes: [
          'categoryId',
          [sequelize.fn('COUNT', sequelize.col('id')), 'count']
        ],
        group: ['categoryId'],
      })
      
      res.json({
        success: true,
        data: {
          stats: { userCount, materialCount, downloadCount, totalIncome },
          incomeTrend,
          categoryDistribution
        }
      })
    } catch (error) {
      console.error('获取仪表盘数据失败:', error)
      res.status(500).json({
        success: false,
        message: '获取仪表盘数据失败'
      })
    }
  }

  // 获取资料列表
  async getMaterials(req, res) {
    try {
      const { page = 1, size = 20, title, categoryId, status } = req.query
      
      const where = {}
      if (title) where.title = { [Op.like]: `%${title}%` }
      if (categoryId) where.categoryId = categoryId
      if (status) where.status = status
      
      const { count, rows } = await Material.findAndCountAll({
        where,
        include: ['category', 'tags'],
        limit: parseInt(size),
        offset: (page - 1) * size,
        order: [['createdAt', 'DESC']]
      })
      
      res.json({
        success: true,
        data: {
          items: rows,
          total: count
        }
      })
    } catch (error) {
      console.error('获取资料列表失败:', error)
      res.status(500).json({
        success: false,
        message: '获取资料列表失败'
      })
    }
  }

  // 更新资料状态
  async updateMaterialStatus(req, res) {
    try {
      const { id } = req.params
      const { status } = req.body
      
      await Material.update(
        { status },
        { where: { id } }
      )
      
      // 记录操作日志
      await Log.create({
        userId: req.user.id,
        action: 'update',
        description: `更新资料状态为${status}`,
        ip: req.ip
      })
      
      res.json({
        success: true,
        message: '资料状态已更新'
      })
    } catch (error) {
      console.error('更新资料状态失败:', error)
      res.status(500).json({
        success: false,
        message: '更新资料状态失败'
      })
    }
  }

  // 删除资料
  async deleteMaterial(req, res) {
    try {
      const { id } = req.params
      
      await Material.destroy({
        where: { id }
      })
      
      // 记录操作日志
      await Log.create({
        userId: req.user.id,
        action: 'delete',
        description: '删除资料',
        ip: req.ip
      })
      
      res.json({
        success: true,
        message: '资料已删除'
      })
    } catch (error) {
      console.error('删除资料失败:', error)
      res.status(500).json({
        success: false,
        message: '删除资料失败'
      })
    }
  }

  // 获取用户列表
  async getUsers(req, res) {
    try {
      const { page = 1, size = 20, keyword, role, status } = req.query
      
      const where = {}
      if (keyword) {
        where[Op.or] = [
          { username: { [Op.like]: `%${keyword}%` } },
          { email: { [Op.like]: `%${keyword}%` } }
        ]
      }
      if (role) where.role = role
      if (status) where.status = status
      
      const { count, rows } = await User.findAndCountAll({
        where,
        attributes: { exclude: ['password'] },
        limit: parseInt(size),
        offset: (page - 1) * size,
        order: [['createdAt', 'DESC']]
      })
      
      res.json({
        success: true,
        data: {
          items: rows,
          total: count
        }
      })
    } catch (error) {
      console.error('获取用户列表失败:', error)
      res.status(500).json({
        success: false,
        message: '获取用户列表失败'
      })
    }
  }

  // 更新用户状态
  async updateUserStatus(req, res) {
    try {
      const { id } = req.params
      const { status, role } = req.body
      
      const updateData = {}
      if (status) updateData.status = status
      if (role) updateData.role = role
      
      await User.update(
        updateData,
        { where: { id } }
      )
      
      // 记录操作日志
      await Log.create({
        userId: req.user.id,
        action: 'update',
        description: `更新用户状态: ${JSON.stringify(updateData)}`,
        ip: req.ip
      })
      
      res.json({
        success: true,
        message: '用户状态已更新'
      })
    } catch (error) {
      console.error('更新用户状态失败:', error)
      res.status(500).json({
        success: false,
        message: '更新用户状态失败'
      })
    }
  }

  // 获取充值记录
  async getRecharges(req, res) {
    try {
      const { page = 1, size = 20 } = req.query
      
      const { count, rows } = await Payment.findAndCountAll({
        where: { type: 'recharge' },
        include: ['user'],
        limit: parseInt(size),
        offset: (page - 1) * size,
        order: [['createdAt', 'DESC']]
      })
      
      res.json({
        success: true,
        data: {
          items: rows,
          total: count
        }
      })
    } catch (error) {
      console.error('获取充值记录失败:', error)
      res.status(500).json({
        success: false,
        message: '获取充值记录失败'
      })
    }
  }

  // 获取消费记录
  async getConsumptions(req, res) {
    try {
      const { page = 1, size = 20 } = req.query
      
      const { count, rows } = await Payment.findAndCountAll({
        where: { type: 'consumption' },
        include: ['user', 'material'],
        limit: parseInt(size),
        offset: (page - 1) * size,
        order: [['createdAt', 'DESC']]
      })
      
      res.json({
        success: true,
        data: {
          items: rows,
          total: count
        }
      })
    } catch (error) {
      console.error('获取消费记录失败:', error)
      res.status(500).json({
        success: false,
        message: '获取消费记录失败'
      })
    }
  }

  // 获取操作日志
  async getOperationLogs(req, res) {
    try {
      const { page = 1, size = 20, username, action, startDate, endDate } = req.query
      
      const where = {}
      if (username) where.username = { [Op.like]: `%${username}%` }
      if (action) where.action = action
      
      if (startDate && endDate) {
        where.createdAt = {
          [Op.between]: [new Date(startDate), new Date(endDate)]
        }
      }
      
      const { count, rows } = await Log.findAndCountAll({
        where,
        include: ['user'],
        limit: parseInt(size),
        offset: (page - 1) * size,
        order: [['createdAt', 'DESC']]
      })
      
      res.json({
        success: true,
        data: {
          items: rows,
          total: count
        }
      })
    } catch (error) {
      console.error('获取操作日志失败:', error)
      res.status(500).json({
        success: false,
        message: '获取操作日志失败'
      })
    }
  }
}

module.exports = new AdminController()